﻿package src {
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.AsyncErrorEvent;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.ui.Mouse;
	
	import src.model.Song;
	/**
	 * ...
	 * @author AT
	 */
	
	public class Candy extends MovieClip {
		public var songXMLFileUrl:String = "data/song.xml";
		
		private var sound_:Sound;
		private var channel_:SoundChannel;
		private var songList_:Array;
		private var playerlistLoader:URLLoader;
		private var songIdx_:int;
		private var position_:Number = 0;
		
		public function Candy() {
			backBtn.addEventListener(MouseEvent.CLICK, songBack);
			playBtn.addEventListener(MouseEvent.CLICK, songPlay);
			pauseBtn.addEventListener(MouseEvent.CLICK, songPause);
			stopBtn.addEventListener(MouseEvent.CLICK, songStop);
			forwardBtn.addEventListener(MouseEvent.CLICK, songForward);
			
			enableButtons(false);
			loadSongs();
		}
		
		private function loadSongs():void {
			playerlistLoader = new URLLoader();
			playerlistLoader.addEventListener(Event.COMPLETE, handleXMLLoadComplete);
			configureListeners(playerlistLoader);
			playerlistLoader.load(new URLRequest(songXMLFileUrl));
		}
		
		private function handleXMLLoadComplete(event:Event):void {
			playerlistLoader.removeEventListener(Event.COMPLETE, handleXMLLoadComplete);
			removeListeners(playerlistLoader);
			var songsXML:XML = new XML(event.target.data);
			setPlayList(songsXML);
			songName.text = "";
			enableButtons(true);
			
			songPlay(null);
		}
		
		private function setPlayList(songListXML:XML):void {
			songList_ = new Array();
			for each(var prop:XML in songListXML.song){
                var song = new Song();
                song.setData(prop.@src, prop.@disp);
				songList_.push(song);
			}
		}
		
		private function songBack(event:MouseEvent):void {
			songIdx_ -= 1;
			if (songIdx_ < 0) songIdx_ = songList_.length - 1;
			
			position_ = 0;
			songPlay(null);
		}
		
		private function songPlay(event:MouseEvent):void {
			if (channel_){
				try {
					channel_.stop();
				} catch (error) {
					trace(error);
				}
			}
			if (sound_) {
				removeListeners(sound_);
				try {
					sound_.close();
				} catch (error) {
					trace(error);
				}
			}
			sound_ = new Sound();
			configureListeners(sound_);
			sound_.load(Song(songList_[songIdx_]).urlRequest);
			
			channel_ = sound_.play(position_);
			channel_.addEventListener(Event.SOUND_COMPLETE, handleSoundComplete);
			//channel_.soundTransform = (mute_mc.isMute)? new SoundTransform(0) : sndTrans;
			cdp_.playCD();
			showPlayButton(false);
			songName.text = "";
		}
		
		private function songPause(event:MouseEvent):void {
			showPlayButton(true);
			songName.text = "PAUSE";
			
			position_ = channel_.position;
			channel_.stop();
		}
		
		private function songStop(event:MouseEvent):void {
			showPlayButton(true);
			cdp_.stopCD();
			songName.text = "STOP";
			
			position_ = 0;
			channel_.stop();
		}
			
		private function songForward(event:MouseEvent):void {
			songIdx_ += 1;
			if (songIdx_ > songList_.length - 1) songIdx_ = 0;
			
			position_ = 0;
			songPlay(null);
		}
			
		private function enableButtons(bol:Boolean):void {
			backBtn.visible = bol;
			playBtn.visible = bol;
			stopBtn.visible = bol;
			forwardBtn.visible = bol;
			if (!bol) pauseBtn.visible = bol;
		}
		
		private function showPlayButton(bol:Boolean):void {
			playBtn.visible = bol;
			pauseBtn.visible = !bol;
		}
		
		private function configureListeners(dispatcher:IEventDispatcher):void {
			//dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ErrorEvent.ERROR, handleError);
			dispatcher.addEventListener(AsyncErrorEvent.ASYNC_ERROR, handleAsyncError);
			dispatcher.addEventListener(NetStatusEvent.NET_STATUS, handleNetStatus);
			dispatcher.addEventListener(ProgressEvent.PROGRESS , handleProgress);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
		}
		
		private function removeListeners(dispatcher:IEventDispatcher):void {
			//dispatcher.removeEventListener(Event.OPEN, openHandler);
			dispatcher.removeEventListener(ErrorEvent.ERROR, handleError);
			dispatcher.removeEventListener(AsyncErrorEvent.ASYNC_ERROR, handleAsyncError);
			dispatcher.removeEventListener(NetStatusEvent.NET_STATUS, handleNetStatus);
			dispatcher.removeEventListener(ProgressEvent.PROGRESS , handleProgress);
			dispatcher.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
			dispatcher.removeEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
			dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, handleIOError);
		}
		
		private function handleSoundComplete(event:Event):void {
			songForward(null);
		}
		
		private function handleError(event:ErrorEvent):void {
			songName.text = "Error";
		}
		
		private function handleAsyncError(event:AsyncErrorEvent):void {
			songName.text = "AsyncError";
		}
		
		private function handleNetStatus(event:NetStatusEvent):void {
			
		}
		
		private function handleProgress(event:ProgressEvent):void {
			if (songList_) {
				if (event.bytesLoaded >= event.bytesTotal) {
					songName.text = Song(songList_[songIdx_]).dispString;
				} else {
					songName.text = Song(songList_[songIdx_]).dispString + " "
						+ int(event.bytesLoaded / event.bytesTotal * 100) + "%";
				}
			} else {
				songName.text = "Loading..." + int(event.bytesLoaded / event.bytesTotal * 100) + "%";
			}
		}
		
		private function handleSecurityError(event:SecurityErrorEvent):void {
			songName.text = "SecurityError";
		}
		
		private function handleHttpStatus(event:HTTPStatusEvent):void {
			
		}
		
		private function handleIOError(event:IOErrorEvent):void {
			songName.text = "IOError" + event.text;
		}
	}
}